<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="search-card">
      <el-form
        size="small"
        :model="queryParams"
        ref="queryParams"
        class="formBox"
        label-width="88px"
      >
        <el-row :gutter="0">
          <el-col :span="5">
            <el-form-item label="设备SN码" prop="snCode">
              <el-input
                v-model="queryParams.snCode"
                placeholder="请输入设备SN码"
                clearable
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input
                v-model="queryParams.deviceName"
                placeholder="请输入设备名称"
                clearable
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="所属商家" prop="merchantId" class="width_100">
              <el-select
                v-model="queryParams.merchantId"
                placeholder="请选择所属商家"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in merchantListList"
                  :key="index"
                  :value="item.id"
                  :label="item.merchantName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="设备是否在线" prop="isOnline" label-width="108px">
              <el-select
                v-model="queryParams.isOnline"
                placeholder="请选择设备是否在线"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.online"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <div class="dis aic">
                <div class="flex_1"></div>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="handleQuery"
                >
                  搜索
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
                  重置
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 按钮 -->
    <el-card class="search-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['merchant:device:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['merchant:device:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-setting"
            size="mini"
            :disabled="multiple"
            @click="restDeviceFun"
            v-hasPermi="['merchant:device:edit']"
            >重置设备</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['merchant:device:export']"
            >导出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="importStatus = true"
            v-hasPermi="['merchant:device:edit']"
            >导入</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </el-card>
    <!-- 列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="deviceList"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备SN码" align="center" prop="snCode" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="学校" align="center" prop="schoolName" />
        <el-table-column label="校区" align="center" prop="campusName" />
        <el-table-column label="所属商家" align="center" prop="merchantName" />
        <el-table-column label="设备型号" align="center" prop="deviceModel" />
        <el-table-column label="设备标签" align="center" prop="deviceTag" />
        <el-table-column label="版本" align="center" prop="version" />
<!--        <el-table-column label="离线数据" align="center" prop="offlineData" />-->
        <el-table-column label="设备是否在线" align="center" prop="isOnline">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.online" :value="scope.row.isOnline" />
          </template>
        </el-table-column>
        <el-table-column
          label="最后在线时间"
          align="center"
          prop="lastOnlineTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.lastOnlineTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="220"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="restDeviceFun(scope.row)"
              v-hasPermi="['merchant:device:edit']"
              >重置设备
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['merchant:device:edit']"
              >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['merchant:device:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="queryForm" :model="form" label-width="180px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="学校名称" prop="schoolId" class="is-required">
              <el-select
                v-model="form.schoolId"
                placeholder="请选择学校名称"
                clearable
                @change="getCampusListsFun"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in schoolList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="校区名称" prop="campusId" class="is-required">
              <el-select
                v-model="form.campusId"
                placeholder="请选择校区名称"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in campusList"
                  :key="index"
                  :value="item.id"
                  :label="item.campusName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="设备SN码" prop="snCode" class="is-required">
              <el-input
                v-model="form.snCode"
                placeholder="请输入设备SN码"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="设备名称" prop="deviceName" class="is-required">
              <el-input
                v-model="form.deviceName"
                placeholder="请输入设备名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="所属商家" prop="merchantId" class="is-required">
              <el-select
                v-model="form.merchantId"
                placeholder="请选择所属商家"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in merchantListList"
                  :key="index"
                  :value="item.id"
                  :label="item.merchantName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="设备型号" prop="deviceModel" class="is-required">
              <el-input
                v-model="form.deviceModel"
                placeholder="请输入设备型号"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="设备标签" prop="deviceTag" class="is-required">
              <el-input
                v-model="form.deviceTag"
                placeholder="请输入设备标签"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="版本" prop="version" class="is-required">
              <el-input
                v-model="form.version"
                placeholder="请输入版本"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                type="textarea"
                placeholder="请输入内容"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 设备导入 -->
    <el-dialog title="设备导入" :visible.sync="importStatus" width="500px" append-to-body>
      <div style="width: 100%">
        <el-button type="primary" @click="xzmb">下载模板</el-button>
        <div style="text-align: center; margin-top: 20px">
          <file-upload @success="fileSuccess" url="/merchant/device/upload" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importStatus = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMerchantList } from "@/api/merchant/merchantList";
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice,
  restDevice,
} from "@/api/merchant/device";
import { schoolListAll } from "@/api/campus/campus.js";
import { getCampusLists } from "@/api/campus/all";

export default {
  name: "Device",
  dicts: ["online"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        snCode: null,
        deviceName: null,
        schoolName: null,
        merchantName: null,
        deviceModel: null,
        deviceTag: null,
        offlineData: null,
        isOnline: null,
        version: null,
        remarks: null,
        createdAt: null,
        createdBy: null,
      },
      // 表单参数
      form: {},
      merchantListList: [],
      importStatus: false,
      schoolList: [],
      campusList: [],
    };
  },
  created() {
    this.getList();
    this.schoolListAllFun();
    this.listMerchantListFun();
  },
  activated() {
    this.$forceUpdate();
  },
  methods: {
    /**获取所有学校列表*/
    schoolListAllFun() {
      schoolListAll().then((res) => {
        if (res.code == 200) {
          this.schoolList = res.data;
        }
      });
    },
    getCampusListsFun() {
      getCampusLists({ schoolId: this.form.schoolId }).then((res) => {
        if (res.code == 200) {
          this.campusList = res.data;
        }
      });
    },
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then((response) => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询商家列表列表 */
    listMerchantListFun() {
      this.loading = true;
      listMerchantList({
        pageNum: 1,
        pageSize: 500,
      }).then((response) => {
        this.merchantListList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        snCode: null,
        deviceName: null,
        schoolName: null,
        schoolId: null,
        merchantName: null,
        merchantId: null,
        deviceModel: null,
        deviceTag: null,
        offlineData: null,
        isOnline: null,
        lastOnlineTime: null,
        status: null,
        version: null,
        remarks: null,
        createdAt: null,
        createdBy: null,
        updatedAt: null,
        updatedBy: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryParams");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDevice(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      var that = this;

      if (!this.form.schoolId) {
        return that.$modal.msgError("请选择学校");
      }
      if (!this.form.campusId) {
        return that.$modal.msgError("请选择校区");
      }
      if (!this.form.snCode) {
        return that.$modal.msgError("请输入设备SN码");
      }
      if (!this.form.deviceName) {
        return that.$modal.msgError("请输入设备名称");
      }
      if (!this.form.merchantId) {
        return that.$modal.msgError("请选择所属商家");
      }
      if (!this.form.deviceModel) {
        return that.$modal.msgError("请输入设备型号");
      }
      if (!this.form.deviceTag) {
        return that.$modal.msgError("请输入设备标签");
      }
      if (!this.form.version) {
        return that.$modal.msgError("请输入版本");
      }
      if (!this.form.deviceModel) {
        return that.$modal.msgError("请输入设备型号");
      }
      if (this.form.id != null) {
        updateDevice(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addDevice(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除该数据项？")
        .then(function () {
          return delDevice(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "merchant/device/export",
        {
          ...this.queryParams,
        },
        "设备" + `_${new Date().getTime()}.xlsx`
      );
    },
    restDeviceFun(options) {
      this.$confirm("此操作将重置设备, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = { ids: (options.id ? [options.id] : this.ids) || this.ids };
          if (data.ids.length == 0) {
            return this.$modal.msgError("请选择设备");
          }
          restDevice(data).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess(res.msg);
            } else {
              this.$modal.msgError(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 上传后返回
    fileSuccess() {
      this.importStatus = false;
      this.queryParams.pageNum = 10;
      this.queryParams.pageSize = 1;
      this.getList();
    },
    xzmb() {
      window.open(
        "https://school.leyibei.com/api/common/downloads?filename=设备导入.xls",
        "_blank"
      );
    },
  },
};
</script>
